package com.roc.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roc.dao.IBaseDao;
import com.roc.dao.ISQLBaseDao;
import com.roc.newPage.IPageDao;
import com.roc.pojo.Operators;
import com.roc.pojo.TblMchtBankAccount;
import com.roc.pojo.TblMchtInf;
import com.roc.service.ServiceException;
import com.roc.service.StrongDeductionsService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.MD5Utils;
import com.roc.util.constant.SysLogType;
@Service
public class StrongDeductionsServiceImpl implements StrongDeductionsService{
	
	private static Logger logger = Logger.getLogger(StrongDeductionsServiceImpl.class);
	
	@Autowired
	private IPageDao pageDao;
	
	@Autowired
	private ISQLBaseDao sqlBaseDao;
	
	@Autowired
	private IBaseDao baseDao;

	@Transactional(rollbackFor = { ServiceException.class })
	@Override
	public synchronized Map<String, Object> modifyDecMoney(Operators logingMerchant,
			String keyStr, String deductionsMoney) throws ServiceException{
		logger.info(logingMerchant.getAccountNo()+"开始放款：keyStr:【"+keyStr+"】,deductionsMoney:【"+deductionsMoney+"】");
		Map<String,Object> resMap = new HashMap<String, Object>();
		List<Object> paramsList = new ArrayList<Object>();
		String selSql = "SELECT T.RESVER6,T.FREEZE_HAD_SUM,T.MCHNT_CD FROM APSTFR.TBL_TFR_MCHNT_FREEZE_LIST T WHERE T.KEY_STR=? ";
		String updSql = "UPDATE APSTFR.TBL_TFR_MCHNT_FREEZE_LIST T SET T.RESVER6=?,T.REC_UPD_TS=systimestamp WHERE T.KEY_STR=?";
		String mchtSelHql = "FROM TblMchtInf T WHERE T.id=?";
		String bankAccountHql = "FROM TblMchtBankAccount T WHERE T.ownerCd=? and T.accountType=? ";
		String inserSettleSql = "insert into t_settle_item (ID, INS_ID_CD, MCHT_CD, MCHT_NAME, TRANS_AMT, TOTAL_NUM, "
				+ "MCHT_FEE, CHL_TRUE_FEE, MCHT_SET_AMT, BANK_NAME, BANK_CODE, ACCOUNT, ACCOUNT_NAME, ACC_TYPE, SETTLEDATE,"
				+ " SETTLEFLAG, SETDATE, FREEZEFLAG, DT_CREATE, DT_UPDATE, REMARK, REMARK1, REMARK2, REMARK3, REMARK4, FREEZE_AMT, "
				+ "UN_FREEZE_AMT,IS_COMBING,SERIAL_NO,COUNT,CHANGE_FLAG,REMARK5) values (?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?)";
		
		try {
			
			/**
			 * 以下计算全部以分为单位
			 */
			
			if("".equals(Constance.Null2EmptyTrim(keyStr))){
				resMap.put("flag", false);
				resMap.put("msg", "keyStr为空");
				return resMap;
			}
			
			if("".equals(Constance.Null2EmptyTrim(deductionsMoney))){
				resMap.put("flag", false);
				resMap.put("msg", "放款金额为空");
				return resMap;
			}
			
			if(new BigDecimal(deductionsMoney).doubleValue()<=0){
				resMap.put("flag", false);
				resMap.put("msg", "放款金额要大于0");
				return resMap;
			}
			
			List<Object> freezeList = pageDao.querySqlAll(selSql, new Object[]{keyStr});
			if(freezeList.size() != 1){//如果freezeList为空，需要抛异常
				throw new ServiceException("查询强扣表数据条数异常,条数为："+freezeList.size());
			}
			
			//已放款金额(分)
			String reserve6 = Constance.Null2EmptyTrim(((Object[])freezeList.get(0))[0]);
			if("".equals(reserve6)){
				reserve6 = "0";
			}
			
			//已冻结金额(分)
			String freezeHadSum = Constance.Null2EmptyTrim(((Object[])freezeList.get(0))[1]);//已冻结金额
			if("".equals(freezeHadSum)){
				freezeHadSum = "0";
			}
			
			String mchtCd = Constance.Null2EmptyTrim(((Object[])freezeList.get(0))[2]);//商户号
			
			//可放款金额=已冻结金额-已放款金额(分)
			long canDecMoney = new BigDecimal(freezeHadSum).subtract(new BigDecimal(reserve6)).longValue();
			
			//本次放款金额(分)
			long dedcMoney = new BigDecimal(deductionsMoney).multiply(new BigDecimal(100)).longValue();//本次放款金额（元）
			
			if(dedcMoney > canDecMoney){
				resMap.put("flag", false);
				resMap.put("msg", "本次放款金额大于可放款金额");
				return resMap;
			}
			
			//放款
			paramsList.add(dedcMoney+Long.parseLong(reserve6));
			paramsList.add(keyStr);
			int updDecMonCount = sqlBaseDao.deleteBySql(updSql, paramsList);
			if(updDecMonCount != 1){
				throw new ServiceException(logingMerchant.getAccountNo()+"强扣放款修改强扣表数据失败,keyStr:【"+keyStr+"】");
			}
			
			Object[] objParams = new Object[]{mchtCd};
			
			//查询商户信息
			List<Object> mchtList = pageDao.queryAll(mchtSelHql, objParams);
			TblMchtInf mcht = (TblMchtInf) mchtList.get(0);
			
			//查询结算信息
			List<Object> bankAccountList = pageDao.queryAll(bankAccountHql, new Object[]{mchtCd,"01"});
			TblMchtBankAccount bankAccount = (TblMchtBankAccount) bankAccountList.get(0);
			
			//保存出款信息
			paramsList.clear();
			paramsList.add(keyStr);
			paramsList.add(mcht.getBankBelongCd());//机构号
			paramsList.add(mcht.getId());//商户号
			paramsList.add(mcht.getNameBusi());//商户名称
			paramsList.add("");//总金额  空着
			paramsList.add("");//总笔数
			paramsList.add("");//商户手续费
			paramsList.add("");//渠道手续费
			paramsList.add(deductionsMoney);//剩余金额=本次放款金额
			paramsList.add(bankAccount.getBankName());//银行名称
			paramsList.add(bankAccount.getBankCode());//联行号
			paramsList.add(bankAccount.getAccount());//账号
			paramsList.add(bankAccount.getName());//账号名称
			if("1".equals(mcht.getApprovalUserName())){//对公对私
				paramsList.add("01");
			}else if("0".equals(mcht.getApprovalUserName())){
				paramsList.add("02");
			}else{
				paramsList.add("");
			}
			String settleDate = DateUtil.getDate(new Date(),0,"yyyyMMdd");
			paramsList.add(settleDate);//结算日期
			paramsList.add("1");//状态 结算完成
			paramsList.add("");//出款日期
			paramsList.add("0");//冻结标识 0-未冻结
			paramsList.add(new Date());//创建日期
			paramsList.add(new Date());//修改日期
			paramsList.add("2");//出款类型   备注(0：普通交易出款，1：扫码出款，2：强扣放款)
			String uniqueKey = mcht.getBankBelongCd()+MD5Utils.MD5Encode(new StringBuffer(settleDate).append(keyStr).append(Constance.generateRanom()).toString());
			paramsList.add(uniqueKey);
			paramsList.add("");
			paramsList.add("");
			paramsList.add("");
			paramsList.add("0.00");//冻结金额
			paramsList.add(deductionsMoney);//放款金额
			paramsList.add("");
			paramsList.add("");
			paramsList.add(0);
			paramsList.add("");
			paramsList.add("");
			int settleCount = sqlBaseDao.deleteBySql(inserSettleSql, paramsList);
			if(settleCount != 1){
				throw new ServiceException(logingMerchant.getAccountNo()+"出款信息保存失败,keyStr:【"+keyStr+"】");
			}
			
			baseDao.addSyslog(SysLogType.INSERT_STRONG_DEDUC.getCode(),
					SysLogType.INSERT_STRONG_DEDUC.getName(),
					logingMerchant.getAccountNo(), 
					"操作员【" + logingMerchant.getAccountNo()+ "】，添加商户【"+mchtCd+"】的强扣放款成功,放款金额为：【"+deductionsMoney+"】");
			
			logger.info(logingMerchant.getAccountNo()+"放款完成：keyStr:【"+keyStr+"】,deductionsMoney:【"+deductionsMoney+"】");
		} catch (Exception e) {
			logger.error("强扣放款异常："+e.getMessage());
			throw new ServiceException(logingMerchant.getAccountNo()+"强扣放款异常");
		}
		resMap.put("flag", true);
		resMap.put("msg", "操作成功");
		return resMap;
	}

	
	
	

}
